package mapper

import (
	"github.com/beego/beego/v2/client/orm"
	"kong-social-api/modules/user/model"
)

type UserMapper struct{}

// 根据手机号码查询用户信息
func (mapper *UserMapper) GetUserByTelephone(telephone string) *model.User {
	// 获取连接对象
	db := orm.NewOrm()
	var user model.User
	err := db.Raw("select * from xk_user where telephone = ?").SetArgs(telephone).QueryRow(&user)
	if err != nil {
		return nil
	}
	return &user
}

// 根据用户名查询用户信息
func (mapper *UserMapper) GetUserByUserName(username string) *model.User {
	// 获取连接对象
	db := orm.NewOrm()
	var user model.User
	err := db.Raw("select * from xk_user where username = ?").SetArgs(username).QueryRow(&user)
	if err != nil {
		return nil
	}
	return &user
}

// 根据用户账号查询用户信息
func (mapper *UserMapper) GetUserByAccount(account string) *model.User {
	// 获取连接对象
	db := orm.NewOrm()
	var user model.User
	err := db.Raw("select * from xk_user where account = ?").SetArgs(account).QueryRow(&user)
	if err != nil {
		return nil
	}
	return &user
}

// 根据用户id查询
func (mapper *UserMapper) GetUserByID(id uint64) *model.User {
	// 创建orm对象
	db := orm.NewOrm()
	// 保存用户
	var user model.User
	err := db.Raw("select * from xk_user where id = ?").SetArgs(id).QueryRow(&user)
	if err != nil {
		return nil
	}
	return &user
}

// 修改用户密码
func (mapper *UserMapper) UpdatePwd(userId uint64, slat string, newPwd string) (flag bool, err error) {
	// 创建orm对象
	db := orm.NewOrm()
	// 开始执行修改密码的sql语句
	exec, err := db.Raw("UPDATE xk_user SET password = ?,slat = ?,update_time = now() WHERE id = ?").SetArgs(newPwd, slat, userId).Exec()
	affected, err := exec.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil
}

// 修改用户资料
func (mapper *UserMapper) UpdateUserInfo(userId uint64, user *model.User) (flag bool, err error) {
	// 创建orm对象
	db := orm.NewOrm()
	// 开始执行修改密码的sql语句
	exec, _ := db.Raw("UPDATE xk_user SET username = ?,nickname = ?,address = ?,sign = ?,bg_img = ?,birth_day = ?,avatar = ?,male = ? , update_time = now() WHERE id = ? ").
		SetArgs(user.UserName, user.NickName, user.Address, user.Sign, user.BgImg, user.BirthDay, user.Avatar, user.Male, user.ID).
		Exec()
	affected, err := exec.RowsAffected()
	if err != nil {
		return false, err
	}
	return affected > 0, nil
}
